package com.lemner.motion.activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lemner.motion.R;
import com.lemner.motion.base.BaseActivity;
import com.lemner.motion.base.BaseListener;
import com.lemner.motion.base.BaseModel;
import com.lemner.motion.bean.BaseBean;
import com.lemner.motion.bean.LoginBean;
import com.lemner.motion.util.BitmapUtils;
import com.lemner.motion.util.FullScreen;
import com.lemner.motion.util.SystemUtils;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Transformation;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

import cn.qqtheme.framework.picker.OptionPicker;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class ChangeUserActivity extends BaseActivity {
    private LinearLayout ll_name,ll_phone,ll_gender;
         private ImageView iv_back,iv_head;
         private TextView tv_name,tv_gender,tv_phone,tv_school,tv_studynum;
         private String studentname,studentid,studentnum,studentpic,studentgender,studentschool,studentphone, path;
         private Uri imgUri,cropImageUri;
         File outputImage,picImage, filesDir;;
          private OptionPicker picker;
    private String[] word = {"男", "女"};
    private ArrayList<String> list=new ArrayList<>();
    @Override
    public int getLayoutFile() {
        return R.layout.activity_change_user;
    }

    @Override
    public void initView() {
        FullScreen.fullScreen(this,0x0020c26f);
        iv_back=(ImageView)findViewById(R.id.iv_back);
        ll_gender=(LinearLayout)findViewById(R.id.ll_gender);
        ll_phone=(LinearLayout)findViewById(R.id.ll_phone);
        ll_name=(LinearLayout)findViewById(R.id.ll_name);
        iv_head=(ImageView)findViewById(R.id.iv_head);
        tv_name=(TextView)findViewById(R.id.tv_name);
        tv_gender=(TextView)findViewById(R.id.tv_gender);
        tv_phone=(TextView)findViewById(R.id.tv_phone);
        tv_school=(TextView)findViewById(R.id.tv_school);
        tv_studynum=(TextView)findViewById(R.id.tv_studynum);
        getUser(LoginActivity.studentid,LoginActivity.session);
        setSex();
    }

    public void loadData(){
        if (studentpic != null && !studentpic.isEmpty()) {
            Picasso.with(ChangeUserActivity.this).load(studentpic).resize(100, 100).transform(new Transformation() {
                @Override
                public Bitmap transform(Bitmap source) {
                    int size = Math.min(source.getWidth(), source.getHeight());
                    int x = (source.getWidth() - size) / 2;
                    int y = (source.getHeight() - size) / 2;
                    Bitmap squaredBitmap = Bitmap.createBitmap(source, x, y, size, size);
                    if (squaredBitmap != source)
                        source.recycle();
                    Bitmap bitmap = Bitmap.createBitmap(size, size, source.getConfig());
                    Canvas canvas = new Canvas(bitmap);
                    Paint paint = new Paint();
                    BitmapShader shader = new BitmapShader(squaredBitmap, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP);
                    paint.setShader(shader);
                    paint.setAntiAlias(true);
                    float r = size / 2f;
                    canvas.drawCircle(r, r, r, paint);
                    squaredBitmap.recycle();
                    return bitmap;
                }

                @Override
                public String key() {
                    return "circle()";
                }
            }).placeholder(R.drawable.pic).into(iv_head);
        }
        if(studentname!=null)
            tv_name.setText(studentname);
        if(studentgender!=null&&studentgender.equals("0"))
            tv_gender.setText("女");
        else
            tv_gender.setText("男");
        if(studentphone!=null)
            tv_phone.setText(studentphone);
        if(studentschool!=null)
            tv_school.setText(studentschool);
        if(studentnum!=null)
          tv_studynum.setText(studentnum);
    }

    @Override
    public void initEvent() {
        iv_back.setOnClickListener(this);
        iv_head.setOnClickListener(this);
        ll_gender.setOnClickListener(this);
        ll_name.setOnClickListener(this);
        ll_phone.setOnClickListener(this);
        tv_school.setOnClickListener(this);
        tv_studynum.setOnClickListener(this);
    }

    @Override
    public void initData() {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.iv_back:
                Intent intent=new Intent(ChangeUserActivity.this,StartRunActivity.class);
                intent.putExtra("flag",true);
                startActivity(intent);
                finish();
                break;
            case R.id.iv_head:
                setupDialog();
                break;
            case R.id.ll_name:
                Intent intent1=new Intent(ChangeUserActivity.this,ChangeNameActivity.class);
                intent1.putExtra("id",studentid);
                startActivity(intent1);
                finish();
                break;
            case R.id.ll_gender:
                picker.setOnOptionPickListener(new OptionPicker.OnOptionPickListener() {
                    @Override
                    public void onOptionPicked(int index, String item) {
                               tv_gender.setText(item);
                               if(item.equals("女")) updateSex("0");
                               else updateSex("1");
                    }
                        });
                picker.show();
                break;
            case R.id.ll_phone:
                Intent intent2=new Intent(ChangeUserActivity.this,ChangePhoneActivity.class);
                intent2.putExtra("id",studentid);
                startActivity(intent2);
                finish();
                break;
        }

    }

    private void setupDialog() {
        final String[] items = {"拍照", "相册"};
        AlertDialog.Builder listDialog = new AlertDialog.Builder(ChangeUserActivity.this);
        listDialog.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                if (i == 0) { //相机
                    savaPhoto();
                    openCamera();
                } else if (i == 1)  //相册
                    openPicture();
            }
        });
        listDialog.show();
    }

    public void openPicture() {
        Intent intent = new Intent(Intent.ACTION_PICK, null);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(intent,2);
    }

    public void savaPhoto(){
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            //路径1：storage/sdcard/Android/data/包名/files
            filesDir = getApplicationContext().getExternalFilesDir("");
        }else{//手机内部存储
            //路径：data/data/包名/files
            filesDir = getApplicationContext().getFilesDir();
        }
        //图片名字用学生id保存，防止别的用户加载本地图片
        outputImage =new File(filesDir,studentid+".png");
        if(outputImage.exists())
            outputImage.delete();
        try {
            outputImage.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if(Build.VERSION.SDK_INT>=24)
            //安卓7.0以上内容提供者
            imgUri= FileProvider.getUriForFile(ChangeUserActivity.this, "com.lemner.motion.takephoto",outputImage);
        else
            imgUri= Uri.fromFile(outputImage);
    }

    private void saveImage(Bitmap bitmap) {
        File filesDir;
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            //路径1：storage/sdcard/Android/data/包名/files
            filesDir = getApplicationContext().getExternalFilesDir("");
        }else{//手机内部存储
            //路径：data/data/包名/files
            filesDir =getApplicationContext().getFilesDir();
        }
        FileOutputStream fos = null;
        try {
            File file = new File(filesDir,studentid+".png");
            fos = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100,fos);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }finally{
            if(fos != null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void openCamera(){
        Intent intent=new Intent("android.media.action.IMAGE_CAPTURE");
        intent.putExtra(MediaStore.EXTRA_OUTPUT,imgUri);
        startActivityForResult(intent,1);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 1:
                if (resultCode == RESULT_OK)
                    startPhotoZoom1(imgUri);
                break;
            case 2:
                if (resultCode == RESULT_OK)
                    if(SystemUtils.isMIUI()){
                        startPhotoZoomMIUI(data.getData());
                    }
                    else
                        startPhotoZoom(data.getData());
                break;
            case 3:
                //相机
                if (resultCode == RESULT_OK) {
                    try {
                        Bitmap bp = BitmapFactory.decodeStream(getContentResolver().openInputStream(cropImageUri));
                        Bitmap bitmap = BitmapUtils.toRoundBitmap(bp);
                        saveImage(bitmap);
                        uploadFile(outputImage);
                        iv_head.setImageBitmap(bitmap);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
                break;
            case 4:
                if (resultCode == RESULT_OK) {
                    if (Build.VERSION.SDK_INT >= 19) {
                        if (null != data) {
                            if(SystemUtils.isMIUI()) {
                                path = getRealImagePathByUri(ChangeUserActivity.this, cropImageUri);
                            }
                            else {
                                 path = getRealImagePathByUri(ChangeUserActivity.this, data.getData());
                            }
                            picImage = new File(path);
                            uploadFile(picImage);
                            displayImage(path);

                            }
                    } else {
                        if (data != null)
                            handleImageDown(data);
                    }
                }
        }
    }

    private void displayImage(String imagePath) {
        if(imagePath!=null){
            Bitmap b=BitmapFactory.decodeFile(imagePath);
            Bitmap bp=BitmapUtils.toRoundBitmap(b);
            saveImage(bp);
            iv_head.setImageBitmap(bp);
        }
        else
            showToast("获取图片失败");
    }

    public  String getRealImagePathByUri(Context context, Uri uri) {
        if(null == uri) {
            return null;
        } else {
            String scheme = uri.getScheme();
            String data = null;
            if(scheme == null) {
                data = uri.getPath();
            } else if("file".equals(scheme)) {
                data = uri.getPath();
            } else if("content".equals(scheme)) {
                Cursor cursor = context.getContentResolver().query(uri, new String[]{"_data"}, (String) null, (String[]) null, (String) null);
                if(null != cursor) {
                    if(cursor.moveToFirst()) {
                        int index = cursor.getColumnIndex("_data");
                        if(index > -1)
                            data = cursor.getString(index);
                    }
                    cursor.close();
                }
            }
            return data;
        }

    }
    //4.4系统以下处理图片方法
    private void handleImageDown(Intent data) {
        Uri uri=data.getData();
        String imagePath=getRealImagePathByUri(ChangeUserActivity.this,uri);
        picImage=new File(imagePath);
        uploadFile(picImage);
        displayImage(imagePath);
    }

    private void startPhotoZoomMIUI(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // crop为true是设置在开启的intent中设置显示的view可以剪裁
        intent.putExtra("crop", "true");
        intent.putExtra("scale", true);
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX,outputY 是剪裁图片的宽高
        intent.putExtra("outputX", 300);
        intent.putExtra("outputY", 300);
        /**
         * 此方法返回的图片只能是小图片（sumsang测试为高宽160px的图片）
         * 故只保存图片Uri，调用时将Uri转换为Bitmap，此方法还可解决miui系统不能return data的问题
         */
        //intent.putExtra("return-data", true);
        //裁剪后的图片Uri路径，uritempFile为Uri类变量
        cropImageUri = Uri.parse("file://" + "/" + Environment.getExternalStorageDirectory().getPath() + "/" +studentid+".png");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, cropImageUri);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true); // no face detection
        startActivityForResult(intent, 4);
    }

    //相机裁剪
    private void startPhotoZoom1(Uri data) {
        cropImageUri=Uri.fromFile(outputImage);
        Intent intent = new Intent("com.android.camera.action.CROP");
        Zoom(data,intent);
        startActivityForResult(intent, 3);
    }
    //相册裁剪
    public void startPhotoZoom(Uri data) {
        File CropPhoto=new File(filesDir,studentid+".png");
        try{
            if(CropPhoto.exists()){
                CropPhoto.delete();
            }
            CropPhoto.createNewFile();
        }catch(IOException e){
            e.printStackTrace();
        }

        Intent intent = new Intent("com.android.camera.action.CROP");
        Zoom(data,intent);
        startActivityForResult(intent, 4);
    }

    public void Zoom(Uri data,Intent intent){
        intent.setDataAndType(data, "image/*");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); //添加这一句表示对目标应用临时授权该Uri所代表的文件
        }
        // 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        intent.putExtra("scale", true);
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        //输出的宽高
        intent.putExtra("outputX", 300);
        intent.putExtra("outputY", 300);
        intent.putExtra("return-data", false);
        //cropImageUri = Uri.fromFile(new File(filesDir,studentid+LoginActivity.session+".png"));
        intent.putExtra(MediaStore.EXTRA_OUTPUT, cropImageUri);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true); // no face detection
    }

    BaseListener<BaseBean> listener=new BaseListener<BaseBean>() {
        @Override
        public void onResponse(BaseBean baseBean) {
            if(baseBean.getErrorCode().equals("0000"))
                forceonline(ChangeUserActivity.this);
            else if(baseBean.getReturnCode().equals("0001"))
                showToast("修改头像成功");
            else
                showToast("修改头像失败");
        }

        @Override
        public void onFail(String msg) {
            showToast(msg);
            showToast("网络请求超时");
        }
    };

    //上传头像去服务器
    private void uploadFile(File file){
        final RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part body = MultipartBody.Part.createFormData("headPicFile", file.getName(), requestFile);
        BaseModel<BaseBean> model=new BaseModel<>();
        retrofit2.Call<BaseBean>call= model.service.updateUser(studentid,studentname,body,LoginActivity.session);
        model.callEnqueue(call,listener);
    }

    BaseListener<LoginBean> listener1=new BaseListener<LoginBean>() {
        @Override
        public void onResponse(LoginBean loginBean) {
            if(loginBean.getErrorCode().equals("0000"))
            forceonline(ChangeUserActivity.this);
            else if(loginBean.getReturnCode().equals("0001")){
                studentname=loginBean.getData().get(0).getStudentName();
                studentnum=loginBean.getData().get(0).getStudentNum();
                studentpic=loginBean.getData().get(0).getStudentPic();
                studentgender=loginBean.getData().get(0).getStudentSex();
                studentschool=loginBean.getData().get(0).getSchoolName();
                studentid=loginBean.getData().get(0).getStudentId();
                studentphone=loginBean.getData().get(0).getPhoneNum();
                loadData();
            }
            else
                showToast("网络请求超时");
        }

        @Override
        public void onFail(String msg) {
            //showToast(msg);
            showToast("网络请求超时");
        }
    };
    public void getUser(String studentid,String session){
        BaseModel<LoginBean> model=new BaseModel<>();
        retrofit2.Call<LoginBean>call=  model.service.getUser(studentid,session);
        model.callEnqueue(call,listener1);
    }

     BaseListener<BaseBean>listener2=new BaseListener<BaseBean>() {
         @Override
         public void onResponse(BaseBean baseBean) {
             if (baseBean.getErrorCode().equals("0000"))
                 forceonline(ChangeUserActivity.this);
             else if (baseBean.getReturnCode().equals("0001")) {
                 showToast("修改性别成功");
             } else
                 showToast("修改性别失败");
         }
         @Override
         public void onFail(String msg) {
                 showToast(msg);
         }
     };

    public void updateSex(String sex){
        BaseModel<BaseBean> model=new BaseModel<>();
        retrofit2.Call<BaseBean>call=  model.service.updatesex(studentid,sex,LoginActivity.session);
        model.callEnqueue(call,listener2);
    }
    public void setSex(){
        for(int i=0;i<word.length;i++){
            list.add(word[i]);
        }
        picker=new OptionPicker(this,list);
        picker.setTextColor(0x5549DCC2);
        picker.setTextSize(20);
        picker.setCanceledOnTouchOutside(true);
        picker.setTitleTextSize(20);
        WindowManager wm = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
        int height = wm.getDefaultDisplay().getHeight();
        picker.setHeight(height/3);
        picker.setCancelText("取消");
        picker.setSubmitText("提交");
    }



}
